package com.abe.basic.android.fragment;


import android.app.AlertDialog;
import android.content.DialogInterface;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.abe.basic.R;
import com.abe.basic.android.CommonWebActivity;
import com.abe.basic.android.common.CollectContract;
import com.abe.basic.android.common.presenter.CollectArticlePresenter;
import com.abe.basic.model.http.HttpArticleEntity;
import com.abe.basic.model.http.HttpCollectArticleEntity;
import com.abe.basic.model.http.HttpPageEntity;
import com.abe.basic.utils.NormalUtils;
import com.abe.gcore.base.DaggerBaseFragment;
import com.abe.gcore.utils.CoreNormalUtils;
import com.google.gson.Gson;
import com.maning.mndialoglibrary.MProgressDialog;
import com.yanzhenjie.recyclerview.swipe.SwipeItemClickListener;
import com.yanzhenjie.recyclerview.swipe.SwipeMenuRecyclerView;
import com.yanzhenjie.recyclerview.swipe.widget.DefaultItemDecoration;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

public class CollectArticleFragment extends DaggerBaseFragment<CollectContract.CollectArticleView, CollectArticlePresenter> implements SwipeRefreshLayout.OnRefreshListener, SwipeItemClickListener, SwipeMenuRecyclerView.LoadMoreListener, CollectContract.CollectArticleView {

    @BindView(R.id.item_rv)
    SwipeMenuRecyclerView itemRv;
    @BindView(R.id.item_swipe_layout)
    SwipeRefreshLayout itemSwipeLayout;

    private CommonAdapter articleAdapter;

    private List<HttpCollectArticleEntity> articleEntities;
    private HttpPageEntity<HttpCollectArticleEntity> pageEntity;

    MProgressDialog mProgressDialog;

    int deletePos = -1;

    @Override
    protected CollectArticlePresenter createPresenter() {
        return new CollectArticlePresenter();
    }

    @Override
    protected int getLayoutResId() {
        return R.layout.item_view_common_recyclerview_swipemenu;
    }

    @Override
    protected void initDatas() {
        mProgressDialog = NormalUtils.creatDialog(getThisContext());
        articleEntities = new ArrayList<>();
        articleAdapter = new CommonAdapter<HttpCollectArticleEntity>(getContext(), R.layout.item_list_home_article, articleEntities) {
            @Override
            protected void convert(ViewHolder holder, final HttpCollectArticleEntity httpArticleEntity, final int position) {
                holder.setText(R.id.item_name, httpArticleEntity.getTitle());
                String sortInfo = TextUtils.isEmpty(httpArticleEntity.getChapterName())
                        ? "无" : httpArticleEntity.getChapterName();
                sortInfo = "分类：" + sortInfo;
                holder.setText(R.id.item_sort, sortInfo);
                holder.setText(R.id.item_author, httpArticleEntity.getAuthor());
                holder.setText(R.id.item_time, httpArticleEntity.getNiceDate());
                holder.getView(R.id.item_image_collect).setBackgroundResource(R.drawable.icon_collection_1);
                holder.setOnClickListener(R.id.item_image_collect, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        //取消收藏操作
                        AlertDialog.Builder builder = new AlertDialog.Builder(getThisContext()).setTitle("提示").setMessage("取消收藏？").setNegativeButton("取消", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                deletePos = position;
                                mPresenter.unCollect(httpArticleEntity.getId(), httpArticleEntity.getOriginId());
                                mProgressDialog.show();
                            }
                        });
                        builder.show();
                    }
                });
            }
        };
        initRV();
        itemSwipeLayout.setRefreshing(false);
        // 第一次加载数据：一定要调用这个方法，否则不会触发加载更多。
        // 第一个参数：表示此次数据是否为空，假如你请求到的list为空(== null || list.size == 0)，那么这里就要true。
        // 第二个参数：表示是否还有更多数据，根据服务器返回给你的page等信息判断是否还有更多，这样可以提供性能，如果不能判断则传true。
        itemRv.loadMoreFinish(false, true);
        mPresenter.getCollectList(0);
        mProgressDialog.show();
    }

    private void initRV() {
        itemSwipeLayout.setOnRefreshListener(this); // 刷新监听。
        itemRv.setLayoutManager(new LinearLayoutManager(getContext()));
        itemRv.addItemDecoration(new DefaultItemDecoration(CoreNormalUtils.getColor(R.color.transparent)));
        itemRv.useDefaultLoadMore(); // 使用默认的加载更多的View。
        itemRv.setLoadMoreListener(this);
        itemRv.setAdapter(articleAdapter);
        articleAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                HttpCollectArticleEntity articleEntity = articleEntities.get(position);
                HashMap<String, Object> map = new HashMap<>();
                map.put("url", articleEntity.getLink());
                map.put("name", articleEntity.getTitle());
                goToActivity(CommonWebActivity.class, map);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
    }

    @Override
    public void onRefresh() {
        mPresenter.getCollectList(0);
    }

    @Override
    public void onLoadMore() {
        mPresenter.getCollectList(pageEntity.getCurPage());
    }

    @Override
    public void onItemClick(View itemView, int position) {

    }

    @Override
    public void onGetCollectArticles(HttpPageEntity<HttpCollectArticleEntity> entity) {
        if (entity == null) return;
        this.pageEntity = entity;
        if (entity.getCurPage() - 1 == 0) {
            articleEntities.clear();
        } else {
            // 数据完更多数据，一定要调用这个方法。
            // 第一个参数：表示此次数据是否为空。
            // 第二个参数：表示是否还有更多数据。
            itemRv.loadMoreFinish(false, true);
        }
        if (entity.getDatas().size() <= 0) {
            itemRv.loadMoreError(0, "没有更多了");
            return;
        }
        articleEntities.addAll(entity.getDatas());
        refreshRV();
    }

    @Override
    public void onRequest(String type, boolean isSucc) {
        switch (type) {
            case "unCollectArticle": {
                if (isSucc) {
                    if (deletePos != -1) {
                        articleEntities.remove(deletePos);
                        refreshRV();
                        deletePos = -1;
                    }
                }
            }
            break;
        }
    }

    private void refreshRV() {
        itemRv.post(new Runnable() {
            @Override
            public void run() {
                articleAdapter.notifyDataSetChanged();
            }
        });
    }

    @Override
    public void onFinish(String type) {
        mProgressDialog.dismiss();
        itemSwipeLayout.setRefreshing(false);
    }

    @Override
    public void showMessage(int Type, String message) {
    }

    @Override
    public void onFaild(String type) {
    }

    public CollectArticleFragment() {
    }

    public static CollectArticleFragment newInstance() {
        return new CollectArticleFragment();
    }
}
